var scripts = [
  null,
  '../assets/js/bootstrap-multiselect.js',
  "../assets/js/fuelux/fuelux.wizard.js",
  '../assets/js/bootstrap-tagsinput.js',
  "../assets/js/jquery.validate.js",
  "../assets/js/date-time/bootstrap-datepicker.js",
  "../assets/js/date-time/bootstrap-timepicker.js",
  '../assets/ueditor/ueditor.config.js',
  '../assets/ueditor/ueditor.all.min.js',
  null
]


$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  jQuery(function ($) {
    const hasValue = (val) => !!val
    const getString = (val) => '' + val
    const doAlert = (val, cb) => bootbox.alert(val, cb)

    const $destinationId = $("#destinationId")
    const $strategyId = $('#strategyId')
    const $mainImg = $('#mainImg')
    const $numOfDays = $('#numOfDays')
    const $travel = $('#travel')
    const $route = $('#route')
    const $startDate = $('#startDate')
    const $noteName = $('#noteName')
    const $add = $('#add')

    const $notesNumCollect = $('#notesNumCollect')
    const $notesNumComment = $('#notesNumComment')
    const $notesNumGood = $('#notesNumGood')
    const $notesNumView = $('#notesNumView')
    const $notesNumShare = $('#notesNumShare')
    const $notesNumPerson = $('#notesNumPerson')
    const $notesPerMoney = $('#notesPerMoney')
    const $notesPlayStyle = $('#notesPlayStyle')

    // 实例化百度编辑诶
    const ue = window.UE.getEditor('editorContainer')

    /**
     * focusIDs 攻略焦点图
     * */
    const focusIDs = [];
    const notesId = $utils.string.getQueryParam("id");
    const templatesForMultiselect = {
      button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
      ul: '<ul class="multiselect-container dropdown-menu"></ul>',
      filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
      filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
      li: '<li><a href="javascript:void(0);"><label></label></a></li>',
      divider: '<li class="multiselect-item divider"></li>',
      liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
    }

    $destinationId.multiselect({
      enableFiltering: true,
      buttonClass: 'btn btn-white btn-primary',
      maxHeight: 200,
      numberDisplayed: 1,
      templates: templatesForMultiselect
    })

    $strategyId.multiselect({
      enableFiltering: true,
      buttonClass: 'btn btn-white btn-primary',
      maxHeight: 200,
      numberDisplayed: 1,
      templates: templatesForMultiselect
    })
    $("#destinationId").change(function (){
      rebuildStrategySelect()
    })
    renderDestination("destinationId");
    $destinationId.multiselect('rebuild');
    rebuildStrategySelect()

    renderStrategy('strategyId')
    $strategyId.multiselect('rebuild')

    function rebuildStrategySelect(cb) {
      const destinationId = $destinationId.val()
      if (!destinationId) return
      const url = $utils.ajax.setUrl("sysNotes/queryStrategyList")
      const requestData = {
        destinationId: destinationId
      }
      axios.post(url, requestData).then(data => {
        if (data.code === '10000') {
          // $strategyIdWrapper.show()
          const list = data.body || []
          renderStrategy('strategyId', list)
          $strategyId.multiselect('rebuild')
          cb && cb()
        } else {
          bootbox.alert('查询攻略列表失败')
        }
      })
    }

    getNotesInfo();

    $("#webuploader-pick").click(function () {
      resourceModel(1, 9, 9, function (data) {//
        $mainImg.attr("src", data[0].src);
        $mainImg.attr("data-id", data[0].id);
      })
    })

    function getNotesInfo() {
      const url = $utils.ajax.setUrl("sysNotes/getNotesById");
      const params = {}
      params.notesId = notesId//攻略Id
      axios.post(url, params).then(function (response) {
        if (response.code === "10000") {
          const body = response.body || {}
          const baseInfo = body.baseInfo || {}
          const resource = body.resource || []
          const typeId = body.typeId || []

          // 显示攻略基本信息
          $('#noteName').val(baseInfo.notesName || '')
          $('#startDate').val(baseInfo.notesStartDate || '')
          $('#numOfDays').val(baseInfo.notesNumDays || '')
          // 途径、行程信息
          $('#travel').val(baseInfo.notesTravel || '')
          $('#route').val(baseInfo.notesRoute || '')


          $notesNumCollect.val(baseInfo.notesNumCollect || 0)
          $notesNumComment.val(baseInfo.notesNumComment || 0)
          $notesNumGood.val(baseInfo.notesNumGood || 0)
          $notesNumView.val(baseInfo.notesNumView || 0)
          $notesNumShare.val(baseInfo.notesNumShare || 0)
          $notesNumPerson.val(baseInfo.notesNumPerson || 0)
          $notesPerMoney.val(baseInfo.notesPerMoney || 0)
          const styles = (baseInfo.notesPlayStyle || '').split(',')
          $notesPlayStyle.tagsinput('items')
          styles.forEach(style => {
            $notesPlayStyle.tagsinput('add', style)
          })

          $destinationId.multiselect('select', baseInfo.destinationId || '')
          rebuildStrategySelect(() => {
            $strategyId.multiselect('select', baseInfo.strategyId || '')
          })
          typeId.forEach((item, idx) => {
            const tempTypeId = item.TYPE_ID || ''
            const $elem = $(`#noteType input[value="${tempTypeId}"]`)
            if ($elem.length === 1) {
              $elem.prop('checked', true)
            }
          })
          // 主图
          const mainImg = resource.filter(item => getString(item.FIRST_FLAG) === '1')
          if (mainImg.length === 1) {
            const $mainImg = $('#mainImg')
            $mainImg.prop('src', mainImg[0].IMAGE_URL)
            $mainImg.attr('data-id', mainImg[0].RESOURCE_ID)
          }
          // 焦点图
          const imgslistFocus = resource.filter(item => getString(item.FIRST_FLAG) === '0')
          if (imgslistFocus.length > 0) {
            let html = ''
            const itemHtml = `
              <li class="item">
                <div class="thumb">
                  <img data-id="{{imgId}}" src="{{imgUrl}}">
                  <span onclick="delNotesImg(this)" class="btn btn-sm btn-white">
                    <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除
                  </span>
                </div>
              </li>
            `
            imgslistFocus.forEach(item => {
              focusIDs.push(item.RESOURCE_ID || '')
              html += itemHtml
                .replace('{{imgId}}', item.RESOURCE_ID || '')
                .replace('{{imgUrl}}', item.IMAGE_URL || '')
            })
            $('#imgslistFocus').append(html)
          }

          // 填充百度编辑器的内容
          ue.ready(() => {
            ue.setContent(baseInfo.notesContents || '')
          })
        } else {
          bootbox.alert('查询游记信息失败！')
        }
      })
    }

    $add.click(updateNotesInfo)

    /**修改游记信息*/
    function updateNotesInfo() {
      if (!validateFields()) return
      const url = $utils.ajax.setUrl("sysNotes/updateNotes");
      const requestData = {
        notesId,
        destinationId: $destinationId.val(),
        notesName: $noteName.val(),
        notesTypes: (() => {
          const arr = []
          $("#noteType input:checked").each(function (index, ele) {
            arr.push($(this).val())
          })
          return arr.join(',')
        })(),
        notesStartDate: $startDate.val(),
        notesNumDays: $numOfDays.val(),
        notesContents: ue.getContent(),
        notesTravel: $travel.val(),
        notesRoute: $route.val(),
        resourceId: $mainImg.attr('data-id'),
        focusedResourcesId: focusIDs.join(','),
        strategyId: $strategyId.val(),
        notesNumCollect: $notesNumCollect.val(),
        notesNumComment: $notesNumComment.val(),
        notesNumGood: $notesNumGood.val(),
        notesNumView: $notesNumView.val(),
        notesNumShare: $notesNumShare.val(),
        notesNumPerson: $notesNumPerson.val(),
        notesPerMoney: $notesPerMoney.val(),
        notesPlayStyle: $notesPlayStyle.val()
      }
      axios.post(url, requestData).then(function (res) {
        if (res.code === "10000") {
          bootbox.alert("修改游记成功", () => {
            window.location.href = '/views/index.html#page/strategy/notes/list'
          })
        } else {
          bootbox.alert("修改游记失败")
        }
      }).catch(() => {
        bootbox.alert('添加游记信息出错了')
      })
    }

    /**游记图片*/
    $("#webuploader-pick-focus").click(function () {
      resourceModel(2, 9, 9, function (data) {
        $.each(data, function (key, val) {
          if ($.inArray(val.id, focusIDs) == -1) {
            focusIDs.push(val.id);
            var html = '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
              '<span onclick="delNotesImg(this,1)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
            $(".imgslist-focus").append(html)
          }
        })
      })
    })

    function delNotesImg(obj) {
      $(obj).parents(".item").remove()
      removeArrItem(focusIDs, $(obj).prev("img").attr("data-id"))
    }

    window.delNotesImg = delNotesImg

    function removeItem(obj) {
      $(obj).parents(".form-group").remove()
    }

    window.removeItem = removeItem;

    function validateFields () {
      const destinationId = getString($destinationId.val())
      const noteName = getString($noteName.val())
      const noteTypes = (() => {
        const arr = []
        $("#noteType input:checked").each(function (index, ele) {
          arr.push($(this).val())
        })
        return arr.join(',')
      })()
      const notesStartDate = getString($startDate.val())
      const notesNumDays = getString($numOfDays.val())
      const content = getString(ue.getContent())
      const travel = getString($travel.val())
      const route = getString($route.val())
      const resourceId = getString($mainImg.attr('data-id'))
      const focuseResourceIdNum = focusIDs.length;
      const focusedResourcesId = focusIDs.join(',')
      const strategyId = $strategyId.val()
      const notesNumCollect = $notesNumCollect.val()
      const notesNumComment = $notesNumComment.val()
      const notesNumGood = $notesNumGood.val()
      const notesNumView = $notesNumView.val()
      const notesNumShare = $notesNumShare.val()
      const notesNumPerson = $notesNumPerson.val()
      const notesPerMoney = $notesPerMoney.val()

      const isInteger = val => /^[0-9]+$/.test(val)
      if (!hasValue(destinationId)) {
        doAlert('请选择目的地！')
        return false
      }
      if (!hasValue(noteName)) {
        doAlert('请输入游记名称！')
        return false
      }
      if (!hasValue(noteTypes)) {
        doAlert('请选择类型！')
        return false
      }
      if (!hasValue(notesStartDate)) {
        doAlert(('请选择出发日期！'))
        return false
      }
      if (!hasValue(notesNumDays)) {
        doAlert('请选择天数！')
        return false
      }
      if (notesNumDays <= 0) {
        doAlert('天数应大于0！')
        return false
      }
      if (!isInteger(notesNumDays)) {
        doAlert('天数应为证书！')
        return false
      }
      if (!hasValue(content)) {
        doAlert('请输入正文！')
        return false
      }
      if (!hasValue(travel)) {
        doAlert('请输入途径！')
        return false
      }
      if (!hasValue(route)) {
        doAlert('请输入行程！')
        return false
      }
      if (!hasValue(resourceId)) {
        doAlert('请选择主图！')
        return false
      }
      if(focuseResourceIdNum!=4){
        doAlert('焦点图请选择四张！')
        return false
      }
      if (!hasValue(focusedResourcesId)) {
        doAlert('请选择焦点图！')
        return false
      }
      if (!hasValue(strategyId)) {
        doAlert('请选择攻略！')
        return false
      }
      if (!isInteger(notesNumCollect)) {
        doAlert('收藏数量应为整数！')
        return false
      }
      if (!isInteger(notesNumComment)) {
        doAlert('评论数量应为整数！')
        return false
      }
      if (!isInteger(notesNumGood)) {
        doAlert('点赞数量应为整数！')
        return false
      }
      if (!isInteger(notesNumView)) {
        doAlert('点赞数量应为整数！')
        return false
      }
      if (!isInteger(notesNumShare)) {
        doAlert('分享数量应为整数！')
        return false
      }
      if (!isInteger(notesNumPerson)) {
        doAlert('人数应为整数!')
        return false
      }
      if (!isInteger(notesPerMoney)) {
        doAlert('人均费用应为整数!')
        return false
      }
      return true
    }

  })
});
